package pers.qianyu.month_202103.date_20210306;

import pers.qianyu.util.model.*;

/**
 * @author mizzle rain
 * @date 2021-03-06 18:10
 */
public class AddInList {
    /**
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList(ListNode head1, ListNode head2) {
        if (head1 == null) return head2;
        if (head2 == null) return head1;
        head1 = reverse(head1);
        head2 = reverse(head2);
        ListNode p1 = head1, p2 = head2, root = new ListNode(-1), t = root;
        int take = 0;
        while (p1 != null && p2 != null) {
            int s = p1.val + p2.val + take;
            if (s >= 10) {
                take = 1;
                s %= 10;
            } else take = 0;
            t.next = new ListNode(s);
            t = t.next;
            p1 = p1.next;
            p2 = p2.next;
        }
        if (p2 != null) p1 = p2;
        while (p1 != null) {
            int s = p1.val + take;
            if (s >= 10) {
                take = 1;
                s %= 10;
            } else take = 0;
            t.next = new ListNode(s);
            t = t.next;
            p1 = p1.next;
        }
        return reverse(root.next);
    }

    private ListNode reverse(ListNode head) {
        if (head == null) return null;
        ListNode p = head, pre = null;
        while (p != null) {
            ListNode t = p.next;
            p.next = pre;
            pre = p;
            p = t;
        }
        return pre;
    }
}
